﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Web;
using Admin.NET.Core;

namespace Admin.NET.Application
{
    /// <summary>
    /// 单据类型维护表服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WareOrderType", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsOrderTypeService : IWmsOrderTypeService, IDynamicApiController, ITransient
    {
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wareOrderTypeRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        /// <summary>
        /// 构造函数
        /// </summary>
        public WmsOrderTypeService(
            IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep,
            IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep,
            IRepository<WmsOrderType, MasterDbContextLocator> wareOrderTypeRep,
            ISysExcelTemplateService sysExcelTemplateService
        )
        {
            _sysDictTypeRep = sysDictTypeRep;
            _sysDictDataRep = sysDictDataRep;
            _wareOrderTypeRep = wareOrderTypeRep;
            _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 不分页查询单据类型维护表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        [NonAction]
        public async Task<List<WmsOrderTypeOutput>> Page([FromQuery] WareOrderTypeSearch input)
        {
            var wareOrderTypes = await _wareOrderTypeRep.DetachedEntities.Where(u => u.Pid == input.Pid)
                //.OrderBy(PageInputOrder.OrderBuilder<WareOrderTypeSearch>(input))
                .OrderBy(u => u.Sort)
                .ProjectToType<WmsOrderTypeOutput>()
                .ToListAsync();
            return wareOrderTypes;
        }

        /// <summary>
        /// 不分页查询单据类型维护表列表
        /// </summary>
        /// <param name="input">单据类型维护表查询参数</param>
        /// <returns>(单据类型维护表)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsOrderTypeOutput>> ListNonPageAsync([FromQuery] WareOrderTypeSearchNonPage input)
        {
            var pPid = input.Pid;
            var wareOrderTypes = await _wareOrderTypeRep.DetachedEntities.Where(u => u.Pid == pPid)
            //.OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .OrderBy(u => u.Sort)
            .ProjectToType<WmsOrderTypeOutput>()
            .ToListAsync();
            return wareOrderTypes;
        }

        /// <summary>
        /// 增加单据类型维护表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWareOrderTypeInput input)
        {
            var wareOrderType = input.Adapt<WmsOrderType>();

            // 判断单据小类的所属车间是否跟单据大类的所属车间一样，添加小类信息
            //if (input.Pid > 0)
            //{
            //    // 根据Pid查询单据大类的所属车间
            //    var orderDaLei = await _wareOrderTypeRep.FirstOrDefaultAsync(z => z.Id == input.Pid);
            //    if (input.LesWorkShopType != orderDaLei.LesWorkShopType)
            //        throw Oops.Oh("小类添加的所属车间要与大类的所属车间一致！");
            //}

            await _wareOrderTypeRep.InsertAsync(wareOrderType);
        }

        /// <summary>
        /// 删除单据类型维护表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWareOrderTypeInput input)
        {
            var wareOrderType = await _wareOrderTypeRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wareOrderTypeRep.DeleteAsync(wareOrderType);
        }

        /// <summary>
        /// 更新单据类型维护表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWareOrderTypeInput input)
        {
            var isExist = await _wareOrderTypeRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wareOrderType = input.Adapt<WmsOrderType>();
            await _wareOrderTypeRep.UpdateAsync(wareOrderType, ignoreNullValues: true);
        }

        /// <summary>
        /// 获取单据类型维护表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        [NonAction]
        public async Task<WmsOrderTypeOutput> Get([FromQuery] QueryeWareOrderTypeInput input)
        {
            return (await _wareOrderTypeRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsOrderTypeOutput>();
        }

        /// <summary>
        /// 获取单据类型维护表列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [NonAction]
        public async Task<List<WmsOrderTypeOutput>> List([FromQuery] WmsOrderTypeInput input)
        {
            return await _wareOrderTypeRep.DetachedEntities.ProjectToType<WmsOrderTypeOutput>().ToListAsync();
        }

        /// <summary>
        /// Excel模板导入单据类型维护表功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        [NonAction]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WareOrderType", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++)
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsOrderTypeOutput> wareOrderTypeList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsOrderTypeOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wareOrderTypeList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsOrderType>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if (!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsOrderType, WmsOrderTypeOutput>(selectKeys);
            List<WmsOrderType> updates = new();
            List<WmsOrderType> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wareOrderTypeExistSubList = _wareOrderTypeRep.Where(filter).Select(selector).ToList();
                    wareOrderTypeExistSubList.ForEach(x =>
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }

                foreach (var wareOrderType in wareOrderTypeList)
                {
                    if (wareOrderType.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wareOrderType.Adapt<WmsOrderType>());
                    }
                    else
                    {
                        adds.Add(wareOrderType.Adapt<WmsOrderType>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wareOrderTypeRep.Update(x));

                var maxId = _wareOrderTypeRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);
                Db.GetDbContext().Set<WmsOrderType>().AddRange(adds);
                Db.GetDbContext().SaveChanges();
            }

            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载单据类型维护表的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        [NonAction]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WareOrderType", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }

        /// <summary>
        /// 根据单据类型维护表查询参数导出Excel
        /// </summary>
        /// <param name="input">单据类型维护表查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        [NonAction]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WareOrderTypeSearchNonPage input)
        {
            var wareOrderTypeList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wareOrderTypeList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers,
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WareOrderType", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
